<?php
namespace Admin\Controller;
use Think\Controller;
class IndexController extends Controller {
 public function index(){
     //微信验证步骤
	 //获取参数$nonce $timestamp $signature echostr
	 $signature=$_GET['signature'];	
	 $nonce=$_GET['nonce'];	
	 $timestamp=$_GET['timestamp'];	
	 $echostr=$_GET['echostr'];	
	 $token='gaosheng';
	 //按照字典排序 sha1加密
	 $tmparr=array($token,$timestamp,$nonce);
	 sort($tmparr,SORT_STRING);
	 $tmpstr=sha1(implode($tmparr));
	 //加密后的字符串和微信的signature对比
	 if($tmpstr==$signature && $echostr){
		 echo $echostr;
		 exit;
	 }else{
		$this->responseMsg();
		 }
    }
    public function temPlate($content){ 
                $touser=$wechatObj->FromUserName;//关注者的openid
                $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                $createtime=time();
                $msgtype='text';
                $content=$content;
                $template="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                           </xml>"; 
            $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
            return $responsestr;
    }
    public function responseMsg(){
      //1.获取到微信推送过来的post数据（xml格式）
        $postStr=$GLOBALS['HTTP_RAW_POST_DATA'];
        //2.处理消息类型，并且设置回复类型和内容
       	if (empty($postStr)){
		echo "";
        	exit;
	}
        libxml_disable_entity_loader(true);//安全考虑
//<xml>
//<ToUserName><![CDATA[toUser]]></ToUserName>
//<FromUserName><![CDATA[FromUser]]></FromUserName>
//<CreateTime>123456789</CreateTime>
//<MsgType><![CDATA[event]]></MsgType>
//<Event><![CDATA[subscribe]]></Event>
//</xml>
        $wechatObj=  simplexml_load_string($postStr);
//        $wechatObj->ToUserName='';
//        $wechatObj->FromUserName='';
//        $wechatObj->CreateTime='';
//        $wechatObj->MsgType='';
//        $wechatObj->Event='';
        //判断该事件是不是订阅的事件推送
       if(strtolower($wechatObj->MsgType=='event')){
            //如果是订阅（关注）
            if(strtolower($wechatObj->Event)=='subscribe'){
                $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                $touser=$wechatObj->FromUserName;//关注者的openid
                $createtime=time();
                $msgtype='text';
                
                $content="欢迎您关注,小高的微信公众号！<a href='http://www.shoujiduoduo.com/'>铃声多多</a>回复tuwen有惊喜^<>^\n普通话服务请按1\nEnglish services请按2\n其他服务请按3";
                $template="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                           </xml>"; 
              $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
              echo $responsestr; 
              
            
           }else  if(strtolower($wechatObj->Event)=='click'){
                 switch (strtolower($wechatObj->EventKey)){ 
                     case 'hotsang':
                         $content="更多经典老歌欢迎您进入--<a href='http://www.shoujiduoduo.com/'>铃声多多</a>--下载您喜欢的专属铃声";
                         break;
                     case 'good':
                         $content="谢谢亲的赞，小猪爱你哦！";
                         break;
                 }
                        $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                        $touser=$wechatObj->FromUserName;//关注者的openid
                        $createtime=time();
                        $msgtype='text';
                        
                        $template="<xml>
                                        <ToUserName><![CDATA[%s]]></ToUserName>
                                        <FromUserName><![CDATA[%s]]></FromUserName>
                                        <CreateTime>%s</CreateTime>
                                        <MsgType><![CDATA[%s]]></MsgType>
                                        <Content><![CDATA[%s]]></Content>
                                       </xml>";
                        $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
                        echo $responsestr;
                     
                } elseif (strtolower($wechatObj->Event)=='scan' ){
                    switch(trim($wechatObj->EventKey)){
                        case 1000:
                            $content='欢迎您扫临时二维码进入本店消费';
                            break;
                        case 2000:
                            $content='欢迎您扫永久二维码进入本店';
                            break;
                    }
                    $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                    $touser=$wechatObj->FromUserName;//关注者的openid
                    $createtime=time();
                    $msgtype='text';
                    
                    $template="<xml>
                                        <ToUserName><![CDATA[%s]]></ToUserName>
                                        <FromUserName><![CDATA[%s]]></FromUserName>
                                        <CreateTime>%s</CreateTime>
                                        <MsgType><![CDATA[%s]]></MsgType>
                                        <Content><![CDATA[%s]]></Content>
                                       </xml>";
                    $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
                    echo $responsestr; 
                }else if(strtolower($wechatObj->Event)=='location' ){
                    $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                    $touser=$wechatObj->FromUserName;//关注者的openid
                    $createtime=time();
                    $msgtype='text';
                    /* <Latitude>23.137466</Latitude>
                    <Longitude>113.352425</Longitude>
                    <Precision>119.385040</Precision> */
                    $latitude=$wechatObj->Latitude;
                    $Longitude=$wechatObj->Longitude;
                    //百度地图api接口  ak(密钥)3f1YHrjuueLgR4ZG2G9GLtcITVeWTWGn
                     $ak="3f1YHrjuueLgR4ZG2G9GLtcITVeWTWGn";
                     $url="http://api.map.baidu.com/geoconv/v1/?coords=".$Longitude.",".$latitude."&from=1&to=5&ak=".$ak;
                    //初始化curl
                    $ch=  curl_init();//初始化成功返回一个句柄
                    //设置参数
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    //执行curl(采集)
                    $json=curl_exec($ch);
                    
                    //回话结束关闭资源
                    curl_close($ch);
                    $data=json_decode($json,true);
                  
                   $latitude =$data['result'][0]['y'];$Longitude=$data['result'][0]['x']; 
                    
             
                     $url="http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=".$latitude.",".$Longitude."&output=json&pois=1&ak=".$ak;
                    //初始化curl
                    $ch=  curl_init();//初始化成功返回一个句柄
                    //设置参数
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    //执行curl(采集)
                    $json=curl_exec($ch);
                    
                    //回话结束关闭资源
                    curl_close($ch);
                    $json=substr($json,29);
            
                    $json=substr($json,0,-1);
                    	
                    $data=json_decode($json,true);
                    $addr1=$data['result']['addressComponent']['country'];//国家
                    $addr2=$data['result']['formatted_address'];//所在地址
                    $addr3=$data['result']['business'];//附近商业地址
                    $content="百度地图提供位置\r当前位置-".$addr1."\r当前地理位置是-".$addr2."\r您附近的商业区-".$addr3;
                    //$content=$latitude.$Longitude;
                    $template="<xml>
                                        <ToUserName><![CDATA[%s]]></ToUserName>
                                        <FromUserName><![CDATA[%s]]></FromUserName>
                                        <CreateTime>%s</CreateTime>
                                        <MsgType><![CDATA[%s]]></MsgType>
                                        <Content><![CDATA[%s]]></Content>
                                       </xml>";
                    $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
                    echo $responsestr;
                }                
            
      }
        //消息回复处理
        
        //回复图文消息
       if($wechatObj->MsgType=='text' && strtolower(trim($wechatObj->Content))=='tuwen'){
          
               $touser=$wechatObj->FromUserName;
               $fromuser=$wechatObj->ToUserName;
               $time=time();
               $type='news';
               $newsarr=array(
                          array(
                             'title'=>'php第一课',
                             'description'=>'php是一门解释型语言，适用于开发中小型网站，开发周期短', 
                             'picurl'=>'https://img.alicdn.com/tps/TB1eREfLVXXXXaHXFXXXXXXXXXX-480-260.png',
                             'url'=>'http://www.imooc.com/'      
                               ),
                           array(
                               'title'=>'慕课网程序员的天堂',
                               'description'=>'慕课网的视频质量很不错，我很喜欢',
                               'picurl'=>'https://img.alicdn.com/tps/TB1eREfLVXXXXaHXFXXXXXXXXXX-480-260.png',
                               'url'=>'http://coding.imooc.com/class/65.html'
                           ),
                           array(
                               'title'=>'江苏交通广播网',
                               'description'=>'江苏交通广播网，您身边的维权专家',
                               'picurl'=>'http://i.vojs.cn/ljh/2014new/images/logo.jpg',
                               'url'=>'http://www.vojs.cn/'
                               ),
                           array(
                               'title'=>'腾讯新闻',
                               'description'=>'大佬云集 一张图带你读懂第三届世界互联网大会',
                               'picurl'=>'http://mat1.gtimg.com/news/news2013/LOGO.jpg',
                               'url'=>'http://news.qq.com/'
                           ),
                           array(
                               'title'=>'php艺术美框架',
                               'description'=>'目前世界上最流行的开源框架之一，艺术之美',
                               'picurl'=>'http://image.golaravel.com/5/1a/d0b8c085dec30605e2c3e9e773d00.png',
                               'url'=>'http://www.golaravel.com/'
                           )
               );
               
               $template="<xml>
               <ToUserName><![CDATA[%s]]></ToUserName>
               <FromUserName><![CDATA[%s]]></FromUserName>
               <CreateTime>%s</CreateTime>
               <MsgType><![CDATA[%s]]></MsgType>
               <ArticleCount>".count($newsarr)."</ArticleCount>
               <Articles>";
               foreach ($newsarr as $k=>$v){
                  $template.="<item>
                   <Title><![CDATA[".$v['title']."]]></Title>
                   <Description><![CDATA[".$v['description']."]]></Description>
                   <PicUrl><![CDATA[".$v['picurl']."]]></PicUrl>
                   <Url><![CDATA[".$v['url']."]]></Url>
                   </item>";
               }
                $template.="</Articles></xml>"; 
               echo $responsestr=sprintf($template,$touser,$fromuser,$time,$type);
                
       }else{
            switch (trim($wechatObj->Content)){
                case 1:
                    $time=time();
                    //$newtime=strtotime("5 April 2017");
                    $newtime=  mktime(0,0,0,4,1,2017);
                    $lasttime=floor(($newtime-$time)/(24*3600));
                    $content="北京时间:\r".  date("Y-m-d H:i:s")."\r距离马克思时间还有".$lasttime.'天';
                    break;
                case 2:
                    $content='English study pay for 50yuan per hours';
                    break;
                case 3:
                    $content='定制服务，需要的联系'."\r<a href='http://www.gaoshengyiyi.cn'>您身边的专属网站</a>";
                    break;
                    
                default:
                    $content='亲爱哒，要输入公众号的提示内容哦！';
            }
                $touser=$wechatObj->FromUserName;//关注者的openid
                $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                $createtime=time();
                $msgtype='text';
                $content=$content;
                $template="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                           </xml>"; 
           echo   $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);
        } 
        //回复图片消息(测试未能成功，使用的media_id是用户发来的)
   /*      if($wechatObj->Msgtype=='text'){
            if(strtolower(trim($wechatObj->Content))=='image'){
            $touser=$wechatObj->FromUserName;
            $fromuser=$wechatObj->ToUserName;
            $createtime=time();
            $type='image';
            $media_id='JmGGVeYbgLhgvGfUUxRYZAjOjYDzYL8diA2wC7Kt5OK2bYXBV6sooleBsf5tcQFd';
            $template="<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Image>
                <MediaId><![CDATA[%s]]></MediaId>
                </Image>
            </xml>";
            $responsestr=  sprintf($template, $touser, $fromuser,$createtime,$type,$media_id);
            echo $responsestr;
            }
             
        } */
        
        //接受普通事件推送图片消息
        if($wechatObj->MsgType=='image'){
             $touser=$wechatObj->FromUserName;//关注者的openid
                $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                $createtime=time();
                $msgtype='text';
                $content=$wechatObj->PicUrl;
                $template="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                           </xml>"; 
           echo   $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);   
        }
        //接收用户发来的语音消息
        if($wechatObj->MsgType=='voice'){
             $touser=$wechatObj->FromUserName;//关注者的openid
                $fromuser=$wechatObj->ToUserName;//公众号自己的openid
                $createtime=time();
                $msgtype='text';
                $content='已经接受您的语音消息了，暂时还不能给您回复语音消息！开发中..';
                $template="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                           </xml>"; 
           echo   $responsestr= sprintf($template,$touser,$fromuser,$createtime,$msgtype,$content);   
        }
        
        
        
   }
       //获取access_token
        //获取accesstoken之前 我们需要使用php强大的工具curl
        public function HttpCurl(){
            //access_token的有效时间是两个小时 一天可以调去2000次
            //存储在session中 无法解决 使用不同的浏览器 调用接口
            //可以存在数据库具体思路
            //存在数据库中生成时间和access-token 每次使用前从数据中调去
            //如果当前时间 减去存储在数据中的时间>7200则重新调用接口生成access_token 并重新存储在session中
            $appid='wx3c511831e869631f';
            $appsecret='29edde853137aed1718db5090ed2f07e';
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;


            //初始化curl
            $ch=  curl_init();//初始化成功返回一个句柄
            //设置参数
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //执行curl(采集)
            $res=curl_exec($ch);
          
            //回话结束关闭资源
            curl_close($ch); 
            if(curl_errno($ch)){
            var_dump(curl_error($ch));
            }
           $arr =json_decode($res,true);
           return $arr; 
        }
        public function getAccessToken(){
           return $this->HttpCurl() ;
        }
        public function getWxIp(){
        
            $access_token="GANdq3wOJ_C4m_L_aEvIHvqXbN7e7b-DzvFp2RYK7iHlibsTfCTRd409W1Azln3dDuM5FqT9GIyPvVe4dmxdMmyiCLOud-4kF1dbnBRAwQsCPMeAHAKXU";
            $url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token;
              $ch=  curl_init();
            //设置参数
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //执行
            $res=curl_exec($ch);
            //关闭资源
            curl_close($ch);
            if(curl_errno($ch)){
                var_dump(curl_error($ch));
            }
            $arr=json_decode($res,TRUE);
            echo '<pre>';
            var_dump($arr);
            echo '</pre>:';
        }
        public function setMenu() {
          $access_token="GANdq3wOJ_C4m_L_aEvIHvqXbN7e7b-DzvFp2RYK7iHlibsTfCTRd409W1Azln3dDuM5FqT9GIyPvVe4dmxdMmyiCLOud-4kF1dbnBRAwQsCPMeAHAKXU";
          //微信接口使用的是post请求数据  对应的 当前使用curl post请求方式
          $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
          //组装菜单数组
         /*  {
              "button":[
              {
                  "type":"click",
                  "name":"今日歌曲",
                  "key":"V1001_TODAY_MUSIC"
              },
              {
                  "name":"菜单",
                  "sub_button":[
                  {
                      "type":"view",
                      "name":"搜索",
                      "url":"http://www.soso.com/"
                  },
                  {
                      "type":"view",
                      "name":"视频",
                      "url":"http://v.qq.com/"
                  },
                  {
                      "type":"click",
                      "name":"赞一下我们",
                      "key":"V1001_GOOD"
                  }]
              }]
          } */
          $data=array(
              "button"=>array(
                               array(
                                   "type"=>"click",
                                   "name"=>"热门铃声",
                                   "key"=>'hotsang'
                               ),
                               array(
                                   "name"=>"菜单",
                                   "sub_button"=>array(
                                                      array(
                                                           "type"=>'view',
                                                           "name"=>'微电影',
                                                           "url"=>"http://www.vmovier.com/" 
                                                          
                                                        ),
                                                        array(
                                                           "type"=>'view',
                                                            "name"=>'手机铃声',
                                                            "url"=>'http://www.shoujiduoduo.com/index.html' 
                                                        ),
                                                        array(
                                                            "type"=>'click',
                                                            'name'=>'赞一下',
                                                            'key'=>'good'
                                                           )
                                                       )
                                   
                                   ),
                               array( 
                                   'type'=>'location_select',
                                   'name'=>'发送位置',
                                   'key'=>'nanjing'
                               )
                   
             )         
          );
         //将数组转成json
         $data=json_encode($data,JSON_UNESCAPED_UNICODE);
         
          //初始化curl
          $ch=curl_init();
          //设置参数
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
          //执行
          $res=curl_exec($ch);//返回json
          //关闭资源
          curl_close($ch);
          if(curl_errno($ch)){
              var_dump(curl_error($ch));
          }
          dump($res);
            
        }
        
        //删除菜单接口
        public function delMenu(){
            $access_token="GANdq3wOJ_C4m_L_aEvIHvqXbN7e7b-DzvFp2RYK7iHlibsTfCTRd409W1Azln3dDuM5FqT9GIyPvVe4dmxdMmyiCLOud-4kF1dbnBRAwQsCPMeAHAKXU";
            
            $url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$access_token;
            //初始化
            $ch=curl_init();
            //设置参数 
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //执行
            $res=curl_exec($ch);
            //关闭资源
            curl_close($ch);
            dump($res);
        }
        //调用接口提示权限不够 (需要申请测试号)
        public function addMedia() {
          
          $access_token="GANdq3wOJ_C4m_L_aEvIHvqXbN7e7b-DzvFp2RYK7iHlibsTfCTRd409W1Azln3dDuM5FqT9GIyPvVe4dmxdMmyiCLOud-4kF1dbnBRAwQsCPMeAHAKXU";
          $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=image";
          //初始化
          $ch=curl_init();
          //设置参数
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          //执行curl
          $res=curl_exec($ch);//ch是一个句柄  返回是一个json
          //结束会话
          curl_close($ch);
          var_dump($res);
        }
    //群发接口测试
    public function sendMsgall(){
        $access_tonken="GANdq3wOJ_C4m_L_aEvIHvqXbN7e7b-DzvFp2RYK7iHlibsTfCTRd409W1Azln3dDuM5FqT9GIyPvVe4dmxdMmyiCLOud-4kF1dbnBRAwQsCPMeAHAKXU";
        $url="https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_tonken;
        /*{
            "touser":"OPENID",
            "text":{
            "content":"CONTENT"
            },
            "msgtype":"text"
        }*/
        /* {
            "touser":"OPENID",
            "mpnews":{
            "media_id":"123dsdajkasd231jhksad"
            },
            "msgtype":"mpnews"
        } */
       /*  {
            "touser":"OPENID",
            "image":{
            "media_id":"123dsdajkasd231jhksad"
            },
            "msgtype":"image"
        } */
        $data=array(
            'touser'=>'ohrkZwuaEh4ADpBrnxaElz7CRbkw',
            'mpnews'=>array(
                    'media_id'=>'123dsdajkasd231jhksad'  
                    ),
            'msgtype'=>'mpnews'
        ); 
        $data=json_encode($data);
        //初始化curl
        $ch=curl_init();
        //设置参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //执行
        $res=curl_exec($ch);
        //关闭资源
        curl_close();
        var_dump($res);
    }
    //回复模板消息 用于向用户发送重要的通知
    public function responseTemMsg(){
      /*   {
            "touser":"OPENID",
            "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
            "url":"http://weixin.qq.com/download",
            "data":{
            "first": {
            "value":"恭喜你购买成功！",
            "color":"#173177"
            },
            "keynote1":{
            "value":"巧克力",
            "color":"#173177"
            },
            "keynote2": {
            "value":"39.8元",
            "color":"#173177"
            },
            "keynote3": {
            "value":"2014年9月22日",
            "color":"#173177"
            },
            "remark":{
            "value":"欢迎再次购买！",
            "color":"#173177"
            }
        }
        } */
        $access_token="SD35nMcmPCqduIrFfawYJjp8UnpAy1vU_GdqqzyjwifTxcjpxb_dAL56-7JPbyiMIBMXxgyuFPzRaBoBUjmFyybfQWudnWZA5-_a3_zpTRR8MPlrjozjyp9uEiUzzNcbYQEjAEAOGU";
        //组装要发送的模板数组
        $data=array(
              'touser'=>'ohrkZwuaEh4ADpBrnxaElz7CRbkw',
            'template_id'=>'RoBDetktVvh5Q-DelQJ2pVrbl5Gpx2BpwwtFcS8yol0',
            'url'=>'https://www.baidu.com/',
              'data'=>array(
                  'name'=>array(
                      'value'=>'万达广场苏果超市pos机器刷卡',
                      'color'=>"#173177"
                  ),
                  'price'=>array(
                      'value'=>'169元',
                      'color'=>"#173177"
                  ),
                  'points'=>array(
                      'value'=>'169分',
                      'color'=>"#173177"
                  ),
                  
                  
                  
              )
        );
        $data=json_encode($data);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        //初始化curl
        $ch=curl_init();
        //设置参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //设置curl post
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //执行curl
        $res=curl_exec($ch);
        //关闭资源
        curl_close($ch);
        var_dump($res);
    }
    public function getbaseCode(){
        $appid="wx3c511831e869631f";
        $redirect_uri=urlencode("http://gaoshengyiyi.cn/index.php/Admin/Index/getUserOpenid");
         //获取code
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect ";
       header("location:".$url); 
     
    }
    public function getUserOpenid(){
       //通过调用getCode方法 访问微信接口 重定向到这个方法
       $code=I('get.code');
       //获取code之后 来换取网页授权的access——token 注意 有效期为5分钟 且只能使用一次
       $appid="wx3c511831e869631f";
       $appsecret="29edde853137aed1718db5090ed2f07e";
       $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
       $ch=curl_init();
          //设置参数
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          //执行curl
          $res=curl_exec($ch);//ch是一个句柄  返回是一个json
          if(curl_errno($ch)){
              var_dump(curl_error($ch));
          }
          //结束会话
          curl_close($ch);
         return  $res;
          //拉取用户信息
          
    }
    public function getusrinfoCode(){
        $appid="wx3c511831e869631f";
        $redirect_uri=urlencode("http://gaoshengyiyi.cn/index.php/Admin/Index/getUserinfo");
        //获取code
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect ";
        header("location:".$url); 
    }
    public function getUserinfo(){
       $result=$this->getUserOpenid();
       $user=json_decode($result,true);
       $access_token=$user['access_token'];
       $openid=$user['openid'];
       $url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
       $ch=curl_init();
       //设置参数
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       //执行curl
       $res=curl_exec($ch);//ch是一个句柄  返回是一个json
       if(curl_errno($ch)){
           var_dump(curl_error($ch));
       }
       //结束会话
       curl_close($ch);
       var_dump($res);
    }
   //微信 js-sdk 
    //生成随机字符串
    public function creatNouce($num=16){
        $nouce=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                     'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                     0,1,2,3,4,5,6,7,8,9
                     );
        $noucestr='';
        for ($i=1;$i<=$num;$i++){
            $index=rand(0, count($nouce)-1);
            $noucestr.=$nouce[$index];
        }
        return  $noucestr;
    }
    public function del(){
        session_destroy();
        var_dump($_SESSION);
    }
    public function getjsApi_Ticket(){
        if($_SESSION['jsapi_ticket'] &&  $_SESSION['jsapi_ticket_expries_in']>time()){
            $jsapi_ticket=$_SESSION['jsapi_ticket'];
        }else{
        $access=$this->getAccessToken();
        $access_token=$access['access_token'];
       
        $url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
        //初始化
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res=curl_exec($ch);
        if(curl_errno($ch)){
            dump(curl_error($ch));
        }
        curl_close($ch);
        
        $res=json_decode($res,true);
        $jsapi_ticket=$res['ticket'];
        $_SESSION['jsapi_ticket']=$jsapi_ticket;
        $_SESSION['jsapi_ticket_expries_in']=time()+7000;
         }
  ;
      return  $jsapi_ticket; 
    }
    //微信js-sdk接口
    public function  wxShare(){
        $appid='wx3c511831e869631f';
        $time=time();
        $noucestr=$this->creatNouce();
        
        //获取signature
        $url='http://www.gaoshengyiyi.cn/index.php/Admin/Index/wxShare';
        $jsapi_ticket=$this->getjsApi_Ticket();
      
        $jsapi_ticketstr="jsapi_ticket=".$jsapi_ticket."&noncestr=".$noucestr."&timestamp=".$time."&url=".$url;
        $signature=sha1($jsapi_ticketstr);
        $this->assign('appid',$appid);
        $this->assign('timestamp',$time);
        $this->assign('noucestr',$noucestr);
        $this->assign('signature',$signature);
        $this->display();
    }
	 public function  wxSharetest(){
        $appid='wx3c511831e869631f';
        $time=time();
        $noucestr=$this->creatNouce();
        
        //获取signature
        $url='http://www.gaoshengyiyi.cn/index.php/Admin/Index/wxShare';
        $jsapi_ticket=$this->getjsApi_Ticket();
      
        $jsapi_ticketstr="jsapi_ticket=".$jsapi_ticket."&noncestr=".$noucestr."&timestamp=".$time."&url=".$url;
        $signature=sha1($jsapi_ticketstr);
        
        $this->assign('appid',$appid);
        $this->assign('timestamp',$time);
        $this->assign('noucestr',$noucestr);
        $this->assign('signature',$signature);
        $this->display();
    }
    
  //微信二维码  生成带参数的二维码
  public function getQRcode(){
      $access_token=$this->getAccessToken();
      $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
/*     
 *   POST数据例子：{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
 */    $data=array(
            'expire_seconds'=>24*60*60*7,//最大可以设置一个月
             'action_name'=> 'QR_SCENE',
              'action_info'=>array(
                   'scene'=>array(
                      'scene_id'=>1000 
                   )
              )
      );
      $data=json_encode($data);
      $ch=curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $res=curl_exec($ch);
      if(curl_errno($ch)){
          dump(curl_error($ch));
      }
      curl_close($ch);
      
      $data=json_decode($res,true);
      $ticket=urlencode($data['ticket']);
      
     $url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
     echo "<img src=".$url." alt='' />";
  }
  
  public function getFQRcode(){
      $access_token=$this->getAccessToken();
      $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
      /*
       *   POST数据例子：{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
       */    $data=array(
           'action_name'=>"QR_LIMIT_SCENE",
           'action_info'=>array(
               'scene'=>array(
                   'scene_id'=>2000
               )
           )
       );
      $data=json_encode($data);
      $ch=curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $res=curl_exec($ch);
      if(curl_errno($ch)){
          dump(curl_error($ch));
      }
      curl_close($ch);
  
      $data=json_decode($res,true);
      $ticket=urlencode($data['ticket']);
  
      $url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
      echo "<img src=".$url." alt='' />";
  }
  //转到上面的扫描二维码关注事件
	
}